package leetcode.dataStructure;

//安全买票
public class Demo24_UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket ticketer = new BuyTicket();
        new Thread(ticketer, "User").start();
        new Thread(ticketer, "Yello Niu").start();

    }
}

class BuyTicket implements Runnable {
    //票
    private int ticketNums = 10;
    boolean flag = true;

    @Override
    public  void run() {
        //买票
        while (flag) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            buy();
        }

    }

    //买票
    private synchronized void buy() {
        //判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }


        //买票
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
    }
}

